//
//  ApprovalProcessViewController.m
//  XTCloud
//
//  Created by QA on 16/8/30.
//  Copyright © 2016年 ShangHai HaoLei Software Technology Co., Ltd. All rights reserved.
//

#import "ApprovalProcessViewController.h"

#import "SKSTableView.h"
#import "MJRefresh.h"
#import "ServiceConnect.h"
#import "NSDictionary+DataFormat.h"

#import "OASendApplyClassItemViewCell.h"
#import "OASendApplyClassViewCell.h"
#import "CustomBadge.h"

#import "NSKeyedArchiverUserLogin.h"
#import "NSDictionary+DataFormat.h"
#import "GEPushViewControllerHelper.h"

#import "OAMyApprovalViewController.h"
#import "OAMyApplyViewController.h"
#import "OAAllApprovalViewController.h"

#import "OASendApplyViewController.h"
#import "QueryMessageService.h"

@interface ApprovalProcessViewController ()<SKSTableViewDelegate>

@property (nonatomic,strong) IBOutlet SKSTableView *tableView;
@property (nonatomic,strong) IBOutlet UIView *tableHeaderView;
@property (strong, nonatomic) NSArray *reslutData;
@property (nonatomic,assign) NSInteger orderContentState;//0加载中，1未找到数据，2加载失败，3加载成功

@property (strong, nonatomic) IBOutlet UIView *ksspView;
@property (strong, nonatomic) IBOutlet UIView *yfsqView;
@property (strong, nonatomic) IBOutlet UIView *syspView;

@property (strong, nonatomic) IBOutlet UIView *ksspImageView;
@property (strong, nonatomic) IBOutlet UIView *yfsqImageView;

@end

@implementation ApprovalProcessViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [self setTitle: @"审批"];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.reslutData = [NSArray array];
    
    self.tableView.SKSTableViewDelegate = self;
    self.tableView.shouldExpandOnlyOneCell = YES;
    self.tableView.tableHeaderView = self.tableHeaderView;
    self.tableView.tableFooterView= [[UIView alloc] init];
    
//    CGFloat width = SuperWidth;
//    CGFloat height = SuperHeight - self.view.frame.origin.x;
//    
//    self.indicatoView=[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
//    _indicatoView.center = CGPointMake(width/2, height/2);
//    _indicatoView.activityIndicatorViewStyle=UIActivityIndicatorViewStyleGray;
//    //_indicatoView.hidesWhenStopped = YES;
//    [self.view addSubview:_indicatoView];
//    
//    self.promptButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, width, height)];
//    [_promptButton setTitle:@"申请模板加载失败，点击重试" forState:UIControlStateNormal];
//    [_promptButton setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
//    _promptButton.titleLabel.font = [UIFont systemFontOfSize:16];
//    [_promptButton addTarget:self action:@selector(promptSender:) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:_promptButton];
    
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(OnTapBtnView:)];
    [self.ksspView addGestureRecognizer:tap1];
    self.ksspView.tag = 1;
    
    UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(OnTapBtnView:)];
    [self.yfsqView addGestureRecognizer:tap2];
    self.yfsqView.tag = 2;
    
    UITapGestureRecognizer *tap3 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(OnTapBtnView:)];
    [self.syspView addGestureRecognizer:tap3];
    self.syspView.tag = 3;
    
//    //审批小图标提示
//    NSDictionary *mDictionary = [QueryMessageService sharedService].getMessageSaveDictionary;
//    NSInteger myapp = [mDictionary objectFormatIntegerForKey:@"myapp"];
//    if(myapp > 0){
//        NSString *value = [NSString stringWithFormat:@"%ld",myapp];
//        CustomBadge *badgeView1 = [CustomBadge customBadgeWithString:value];
//        [self.ksspImageView addSubview:badgeView1];
//        [badgeView1 makeConstraints:^(MASConstraintMaker *make) {
//            make.top.equalTo(self.ksspImageView);
//            make.right.equalTo(self.ksspImageView);
//            make.height.equalTo(24);
//            make.width.equalTo(24);
//        }];
//    }
//    
//    //我的申请小图标提示
//    NSInteger mysq = [mDictionary objectFormatIntegerForKey:@"mysq"];
//    if(mysq > 0){
//        NSString *value = [NSString stringWithFormat:@"%ld",mysq];
//        CustomBadge *badgeView2 = [CustomBadge customBadgeWithString:value];
//        [self.yfsqImageView addSubview:badgeView2];
//        [badgeView2 makeConstraints:^(MASConstraintMaker *make) {
//            make.top.equalTo(self.yfsqImageView);
//            make.right.equalTo(self.yfsqImageView);
//            make.height.equalTo(24);
//            make.width.equalTo(24);
//        }];
//    }
    
    //获取网络数据
    [self getApplyClassNetWorkData];
}

- (void)getApplyClassNetWorkData
{
    ServiceConnect *content = [[ServiceConnect alloc] initWithMethodName:@"OA_getApprovalTemplateType" dataArray:nil];
    [content startConnectNetworkCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        //添加数据，刷新页面
        if (result.resultArray && result.resultArray.count>0) {
            self.reslutData = result.resultArray;
            self.orderContentState = 3;
        } else {
            self.orderContentState = 1;
        }
        [self.tableView refreshData];
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        self.orderContentState = 2;
        [self.tableView refreshData];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        self.orderContentState = 2;
        [self.tableView refreshData];
    }];
}

- (void)promptSender:(id)sender
{
    //获取合同数据
    [self getApplyClassNetWorkData];
}

#pragma mark -点击事件

-(void)OnTapBtnView:(UITapGestureRecognizer *)sender
{
    NSLog(@"tag:%ld",sender.view.tag);
    
    if(sender.view.tag == 1) {//快速审批
        NSArray *menuArray = [ModuleAuthorityEntity MR_findByAttribute:@"permissionsMark" withValue:@"P_OASP_KSSP"];
        if(menuArray.count > 0) {
            OAMyApprovalViewController *view = [[OAMyApprovalViewController alloc] init];
            [self.navigationController pushViewController:view animated:YES];
        } else {
            [self showErrorHUDText:@"无操作权限" dismissAfterDelay:0];
        }
        
    } else if(sender.view.tag == 2) {//我的申请
        NSArray *menuArray = [ModuleAuthorityEntity MR_findByAttribute:@"permissionsMark" withValue:@"P_OASP_SQ"];
        if(menuArray.count > 0) {
            OAMyApplyViewController *view = [[OAMyApplyViewController alloc] init];
            [self.navigationController pushViewController:view animated:YES];
        } else {
            [self showErrorHUDText:@"无操作权限" dismissAfterDelay:0];
        }
        
    } else if(sender.view.tag == 3) {//所有审批
        NSArray *menuArray = [ModuleAuthorityEntity MR_findByAttribute:@"permissionsMark" withValue:@"P_OASP_SYSP"];
        if(menuArray.count > 0) {
            OAAllApprovalViewController *view = [[OAAllApprovalViewController alloc] init];
            [self.navigationController pushViewController:view animated:YES];
        } else {
            [self showErrorHUDText:@"无操作权限" dismissAfterDelay:0];
        }
    }
    
}

#pragma mark -获取当前其他数据

- (void)getOtherListData:(NSDictionary*)dictionary
{
    NSNumber *templateId = [dictionary objectFormatForKey:@"id"];
    ServiceParametModel *model = [[ServiceParametModel alloc] init];
    [model setValue:templateId forKey:@"templateId"];
    
    ServiceConnect *content = [[ServiceConnect alloc] initWithMethodName:@"OA_getProcessByTemplateId" dataArray:model];
    [content showMBProgressHUD:self.navigationController labelText:@"正在处理"];
    [content startConnectNetworkCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        if (result.resultArray && result.resultArray.count>0) {
            NSArray *resultValue = @[dictionary,result.resultArray];
            //关闭页面，返回数据
            OASendApplyViewController *view = [[OASendApplyViewController alloc] initWithValue:resultValue];
            [self.navigationController pushViewController:view animated:YES];
        } else {
            [self showErrorHUDText:@"处理失败"];
        }
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [self showErrorHUDText:@"处理失败"];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [self showErrorHUDText:@"网络异常"];
    }];
    
}

#pragma mark - UIBarButtonItem Event

- (void)selectSelector:(id)selector
{
    
}

#pragma mark - Table view data source

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger count = self.reslutData.count;
    return count == 0 ? 1 : count;
}

- (NSInteger)tableView:(SKSTableView *)tableView numberOfSubRowsAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger count = self.reslutData.count;
    if(count <= 0) return 1;
    
    NSDictionary *mDictionary = [self.reslutData objectAtIndex:indexPath.row];
    NSArray *itemArray = [mDictionary objectFormatForKey:@"template"];
    return itemArray.count;
}

- (UITableViewCell *)tableView:(SKSTableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.orderContentState == 3) {
        static NSString *CellIdentifier = @"OASendApplyClassViewCellClass";
        OASendApplyClassViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (!cell)
            cell = [[OASendApplyClassViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        
        [cell setIsShowAccessory:YES];
        
        NSDictionary *mDictionary = [self.reslutData objectAtIndex:indexPath.row];
        cell.titleLable.text = [mDictionary objectFormatStringForKey:@"mc"];
        return cell;
        
    } else {
        SKSTableViewCell *cell = [[SKSTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MTCClienterDetailHT"];
        cell.contentView.frame = CGRectMake(0, 0, SuperWidth, 55);
        
        if(self.orderContentState == 0) {//加载进度条
            UIActivityIndicatorView *act=[[UIActivityIndicatorView  alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
            act.center = CGPointMake(SuperWidth/2, 30.0f);
            act.activityIndicatorViewStyle=UIActivityIndicatorViewStyleGray;
            act.hidesWhenStopped = YES;
            [act startAnimating];
            [cell.contentView addSubview:act];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
        } else if(self.orderContentState == 1){//显示无数据提示
            UILabel* label = [[UILabel alloc] initWithFrame:cell.contentView.frame];
            label.text = @"暂无申请模板";
            label.font = [UIFont fontWithName:@"Arial" size:16];
            label.textColor = [UIColor lightGrayColor];
            label.textAlignment = NSTextAlignmentCenter;
            [cell.contentView addSubview:label];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
        } else if(self.orderContentState == 2){//显示失败提示
            UILabel* label = [[UILabel alloc] initWithFrame:cell.contentView.frame];
            label.text = @"加载申请失败，点击重试";
            label.font = [UIFont fontWithName:@"Arial" size:16];
            label.textColor = [UIColor lightGrayColor];
            label.textAlignment = NSTextAlignmentCenter;
            [cell.contentView addSubview:label];
        }
        return cell;
    }
}

- (UITableViewCell *)tableView:(SKSTableView *)tableView cellForSubRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row >= self.reslutData.count){
        static NSString *CellIdentifier = @"UITableViewCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (!cell)
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        return cell;
        
    } else {
        static NSString *CellIdentifier = @"OASendApplyClassItemViewCell";
        OASendApplyClassItemViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (!cell)
            cell = [[OASendApplyClassItemViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        
        NSDictionary *mDictionary = [self.reslutData objectAtIndex:indexPath.row];
        NSArray *itemArray = [mDictionary objectFormatForKey:@"template"];
        NSDictionary *itemValue = [itemArray objectAtIndex:indexPath.subRow-1];
        
        cell.titleLable.text = [itemValue objectFormatStringForKey:@"templatename"];
        return cell;
    }
}

- (CGFloat)tableView:(SKSTableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row >= self.reslutData.count) return 56;
    return 44;
}

- (CGFloat)tableView:(SKSTableView *)tableView heightForSubRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"Section: %ld, Row:%ld, Subrow:%ld", (long)indexPath.section, indexPath.row, (long)indexPath.subRow);
    
    //加载失败执行
    if(self.orderContentState == 2) {
        self.orderContentState = 0;
        [self.tableView reloadData];
        [self getApplyClassNetWorkData];
    }
}

- (void)tableView:(SKSTableView *)tableView didSelectSubRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"Section: %ld, Row:%ld, Subrow:%ld", indexPath.section, (long)indexPath.row, (long)indexPath.subRow);
    if(self.orderContentState != 3) return;
    
    //发起申请权限判断
    NSArray *menuArray = [ModuleAuthorityEntity MR_findByAttribute:@"permissionsMark" withValue:@"P_OASP_FQSQ"];
    if(menuArray.count > 0){
        NSDictionary *mDictionary = [self.reslutData objectAtIndex:indexPath.row];
        NSArray *itemArray = [mDictionary objectFormatForKey:@"template"];
        NSDictionary *itemValue = [itemArray objectAtIndex:indexPath.subRow-1];
        [self getOtherListData:itemValue];
    } else{
        [self showErrorHUDText:@"无操作权限" dismissAfterDelay:0];
    }
    
}

@end
